import { uploadParamsType } from '../type';
import { httpRequest } from '../utils/httpRequest';

export function upload(
  instance: any,
  params: uploadParamsType,
  bucketName?: string
): Promise<any> {
  return new Promise((resolve, reject) => {
    const file = params.file;
    if (!file) return reject('未提供上传文件');

    const { maxSize = -1, partSize = -1, queueLength = 1 } = params;

    // 是否采用分片
    const isPart = maxSize > 0 && file.size > maxSize;

    // 非切片环境
    if (!isPart) {
      let uploadAbort: any = {
        instance: null,
      };
      uploadAbort.cancel = function () {
        uploadAbort.instance?.abort();
      };
      params.onCancel && params.onCancel(uploadAbort);
      let signInfo = instance.createV4SignedUrlSync({
        Bucket: bucketName,
        Key: params.fileName,
        Expires: 60 * 60 * 24,
        Method: 'PUT',
      });
      if (!signInfo) return reject('预签名生成失败');
      httpRequest({
        url: signInfo.SignedUrl,
        method: 'put',
        data: file,
        xhrInstance: uploadAbort,
        onProgress: params.onUploadProgress,
      })
        .then((res) => {
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    }

    // 切片环境
    if (isPart) {
      instance.uploadFile(
        {
          Bucket: bucketName,
          Key: params.fileName,
          SourceFile: file,
          PartSize: isPart ? partSize : file.size,
          TaskNum: isPart ? queueLength : 1,
          ProgressCallback(transferredAmount: number, totalAmount: number) {
            params.onUploadProgress &&
              params.onUploadProgress({
                loaded: transferredAmount,
                total: totalAmount,
              });
          },
          ResumeCallback: function (resumeHook: any) {
            params.onCancel && params.onCancel(resumeHook);
          },
        },
        (err: any, result: any) => {
          resolve(result);
          if (err) {
            reject(err);
          }
        }
      );
    }
  });
}
